package com.easylinkin.linkappapi.config.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.config.entity.Config;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.config.service.SysDictService;
import com.easylinkin.linkappapi.config.vo.SysDictQueryRequestVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import java.util.List;

/**
 * 数据字典/数据字典类型
 */
@RequestMapping("sys/dict")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysDictController {

    final String moduleName = "系统管理-数据字典分类";

    private final SysDictService service;

    private final SysDictItemService sysDictItemService;

    /**
     * 数据字典分类列表
     *
     * @param requestVo 数据字典分类查询对象
     */
    @SuppressWarnings("unchecked")
    @PostMapping("getPage")
    @ApiOperation("查询分页")
    public RestMessage page(@RequestBody RequestModel<SysDictQueryRequestVo> requestModel) {
        IPage page = service.page(requestModel.getPage(), requestModel.getCustomQueryParams().getQueryWrapper());
        return RestBuilders.successBuilder(page).build();
    }

    /**
     * 新增数据字典分类
     *
     * @param requestVo 数据字典分类对象
     */
    @RequestMapping(method = RequestMethod.POST)
    public RestMessage create(@RequestBody @Validated SysDictQueryRequestVo requestVo) {
        // 校验code是否重复
        SysDict one = service.getOne(new LambdaQueryWrapper<SysDict>().eq(SysDict::getDictCode, requestVo.getDictCode()));
        if (one!=null) {
            throw new BusinessException("数据字典分类code已存在");
        }
        return RestBuilders.successBuilder(service.save(requestVo.toEntity())).build();
    }

    /**
     * 数据字典分类详情
     *
     * @param id 数据字典分类Id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public RestMessage get(@PathVariable Long id) {
        return RestBuilders.successBuilder(service.getById(id)).build();
    }

    /**
     * 更新数据字典分类
     *
     * @param id 数据字典分类Id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public RestMessage update(@PathVariable Long id, @RequestBody @Validated SysDictQueryRequestVo requestVo) {
        // 校验code是否重复
        SysDict one = service.getOne(new LambdaQueryWrapper<SysDict>()
                .eq(SysDict::getDictCode, requestVo.getDictCode())
                .ne(SysDict::getId, id));
        if (one != null) {
            throw new BusinessException("数据字典分类code已存在");
        }
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("dict_id_", id);
        updateWrapper.set("is_sync_", false);

        sysDictItemService.update(updateWrapper);
        SysDict entity = requestVo.toEntity();
        entity.setId(id);
        return RestBuilders.successBuilder(service.updateById(entity)).build();
    }


    /**
     * 删除数据字典分类
     *
     * @param id 数据字典分类Id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public RestMessage delete(@PathVariable Long id) {
        // 校验是否有子项，有子项不允许删除
//        Boolean exists = sysDictItemService.exists(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId,id));
//        if(exists){
//            throw new ApiException(AdminErrorCode.C1002);
//        }
        service.removeById(id);
        sysDictItemService.deleteByDictId(id);
        return RestBuilders.successBuilder().build();
    }


    /**
     * 根据数据字典code查询数据字典明细
     *
     * @param code 数据字典分类code
     */
    @RequestMapping(value = "/getDicItem/{code}", method = RequestMethod.GET)
    public RestMessage getDicItem(@PathVariable String code) {
        List<SysDictItem> list = null;
        SysDict sd = service.getOne(new LambdaQueryWrapper<SysDict>().eq(SysDict::getDictCode, code));
        if (sd != null) {
            // 根据数据字典id查询子项列表
            list = sysDictItemService.list(new LambdaQueryWrapper<SysDictItem>()
                    .eq(SysDictItem::getDictId, sd.getId())
                .eq(SysDictItem::getStatus, 1)
                .orderByAsc(SysDictItem::getSortOrder));
        }
        return RestBuilders.successBuilder(list).build();
    }

}